<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><meta name="generator" content="Hexo 4.2.1"><link rel="apple-touch-icon" sizes="180x180" href="/uploads/apple-touch-icon.png"><link rel="icon" type="image/png" sizes="32x32" href="/uploads/images/icons/icon-96x96.png"><link rel="icon" type="image/png" sizes="16x16" href="/uploads/images/icons/icon-72x72.png"><link rel="mask-icon" href="/uploads/images/icons/icon-128x128.png" color="#222"><link rel="manifest" href="/uploads/manifest.json"><meta name="google-site-verification" content="Xk9YWz2-rBE9P5__qdWz3nUr4zb9bIDSdANHpezjB04"><link rel="stylesheet" href="/css/main.css"><link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css"><link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/pace-js/themes/blue/pace-theme-minimal.css"><script src="https://cdn.jsdelivr.net/npm/pace-js/pace.min.js"></script><script id="hexo-configurations">var NexT=window.NexT||{},CONFIG={hostname:"csjiabin.github.io",root:"/",scheme:"Pisces",version:"7.8.0",exturl:!1,sidebar:{position:"left",display:"post",padding:18,offset:12,onmobile:!1},copycode:{enable:!0,show_result:!0,style:null},back2top:{enable:!0,sidebar:!1,scrollpercent:!0},bookmark:{enable:!1,color:"#222",save:"auto"},fancybox:!0,mediumzoom:!1,lazyload:!0,pangu:!0,comments:{style:"tabs",active:null,storage:!0,lazyload:!0,nav:null},algolia:{appID:"247B2CASJT",apiKey:"35251fd833510bf375580b718064be3a",indexName:"csjiabin.github.io",hits:{per_page:10},labels:{input_placeholder:"搜索",hits_empty:"未发现与 「${query}」相关的内容",hits_stats:"${hits} 条相关条目, 使用了 ${time} 毫秒"}},localsearch:{enable:!1,trigger:"auto",top_n_per_article:1,unescape:!1,preload:!1},motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},path:"search.xml"}</script><meta name="description" content="浮点数取整12345const x &#x3D; 123.4545;x &gt;&gt; 0; &#x2F;&#x2F; 123~~x; &#x2F;&#x2F; 123x | 0; &#x2F;&#x2F; 123Math.floor(x); &#x2F;&#x2F; 123   注意：前三种方法只适用于32个位整数，对于负数的处理上和 Math.floor是不同的。"><meta property="og:type" content="article"><meta property="og:title" content="JavaScript有用的代码片段和trick"><meta property="og:url" content="https://csjiabin.github.io/2018/08/22/JavaScript%E6%9C%89%E7%94%A8%E7%9A%84%E4%BB%A3%E7%A0%81%E7%89%87%E6%AE%B5%E5%92%8Ctrick/index.html"><meta property="og:site_name" content="CSjiabin&#39;s Blog"><meta property="og:description" content="浮点数取整12345const x &#x3D; 123.4545;x &gt;&gt; 0; &#x2F;&#x2F; 123~~x; &#x2F;&#x2F; 123x | 0; &#x2F;&#x2F; 123Math.floor(x); &#x2F;&#x2F; 123   注意：前三种方法只适用于32个位整数，对于负数的处理上和 Math.floor是不同的。"><meta property="og:locale" content="zh_CN"><meta property="article:published_time" content="2018-08-22T13:51:29.000Z"><meta property="article:modified_time" content="2020-11-02T09:26:56.674Z"><meta property="article:author" content="csjiabin"><meta property="article:tag" content="js"><meta name="twitter:card" content="summary"><link rel="canonical" href="https://csjiabin.github.io/2018/08/22/JavaScript%E6%9C%89%E7%94%A8%E7%9A%84%E4%BB%A3%E7%A0%81%E7%89%87%E6%AE%B5%E5%92%8Ctrick/"><script id="page-configurations">CONFIG.page={sidebar:"",isHome:!1,isPost:!0,lang:"zh-CN"}</script><title>JavaScript有用的代码片段和trick | CSjiabin's Blog</title><script async src="https://www.googletagmanager.com/gtag/js?id=UA-124238838-1"></script><script>if(CONFIG.hostname===location.hostname){function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","UA-124238838-1")}</script><script>var _hmt=_hmt||[];!function(){var e=document.createElement("script");e.src="https://hm.baidu.com/hm.js?2620e69674d25088f870bef114e8ff89";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t)}()</script><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-header,.use-motion .comments,.use-motion .menu-item,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript><link rel="alternate" href="/atom.xml" title="CSjiabin's Blog" type="application/atom+xml"></head><body itemscope itemtype="http://schema.org/WebPage"> <img class="bg-image" src="/uploads/bg.jpg"><div class="container use-motion"><div class="headband"></div><header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-container"><div class="site-nav-toggle"><div class="toggle" aria-label="切换导航栏"><span class="toggle-line toggle-line-first"></span><span class="toggle-line toggle-line-middle"></span><span class="toggle-line toggle-line-last"></span></div></div><div class="site-meta"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span><h1 class="site-title">CSjiabin's Blog</h1><span class="logo-line-after"><i></i></span></a><p class="site-subtitle" itemprop="description">Goals determine what you going to be!!</p></div><div class="site-nav-right"><div class="toggle popup-trigger"><i class="fa fa-search fa-fw fa-lg"></i></div></div></div><nav class="site-nav"><ul id="menu" class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i> 首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i> 关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i> 标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i> 分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i> 归档</a></li><li class="menu-item menu-item-search"><a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i> 搜索</a></li></ul></nav><div class="search-pop-overlay"><div class="popup search-popup"><div class="search-header"><span class="search-icon"><i class="fa fa-search"></i></span><div class="search-input-container"></div><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span></div><div class="algolia-results"><div id="algolia-stats"></div><div id="algolia-hits"></div><div id="algolia-pagination" class="algolia-pagination"></div></div></div></div></div></header><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span>0%</span></div> <a href="https://github.com/csjiabin" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0 0 115 115 130 115 142 142 250 250 250 0Z"></path><path d="M128.3 109C113.8 99.7 119 89.6 119 89.6 122 82.7 120.5 78.6 120.5 78.6 119.2 72 123.4 76.3 123.4 76.3 127.3 80.9 125.5 87.3 125.5 87.3 122.9 97.6 130.6 101.9 134.4 103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"></path><path d="M115 115C114.9 115.1 118.7 116.5 119.8 115.4L133.7 101.6C136.9 99.2 139.9 98.4 142.2 98.6 133.8 88 127.5 74.4 143.8 58 148.5 53.4 154 51.2 159.7 51 160.3 49.4 163.2 43.6 171.4 40.1 171.4 40.1 176.1 42.5 178.8 56.2 183.1 58.6 187.2 61.8 190.9 65.4 194.5 69 197.7 73.2 200.1 77.6 213.8 80.2 216.3 84.9 216.3 84.9 212.7 93.1 206.9 96 205.4 96.6 205.1 102.4 203 107.8 198.3 112.5 181.9 128.9 168.3 122.5 157.7 114.1 157.9 116.9 156.7 120.9 152.7 124.9L141 136.5C139.8 137.7 141.6 141.9 141.8 141.8Z" fill="currentColor" class="octo-body"></path></svg></a><main class="main"><div class="main-inner"><div class="content-wrap"><div class="content post posts-expand"><article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN"><link itemprop="mainEntityOfPage" href="https://csjiabin.github.io/2018/08/22/JavaScript%E6%9C%89%E7%94%A8%E7%9A%84%E4%BB%A3%E7%A0%81%E7%89%87%E6%AE%B5%E5%92%8Ctrick/"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="image" content="https://avatars0.githubusercontent.com/u/20592953"><meta itemprop="name" content="csjiabin"><meta itemprop="description" content="I never consider ease and joyfulness as the purpose of life itself."></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="CSjiabin's Blog"></span><header class="post-header"><h1 class="post-title" itemprop="name headline"> JavaScript有用的代码片段和trick</h1><div class="post-meta"><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-calendar"></i></span> <span class="post-meta-item-text">发表于</span> <time title="创建时间：2018-08-22 21:51:29" itemprop="dateCreated datePublished" datetime="2018-08-22T21:51:29+08:00">2018-08-22</time></span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-folder"></i></span> <span class="post-meta-item-text">分类于</span> <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/JavaScript/" itemprop="url" rel="index"><span itemprop="name">JavaScript</span></a></span></span><span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span> <span class="post-meta-item-text">阅读次数：</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-item"><span class="post-meta-item-icon"><i class="far fa-comment"></i></span> <span class="post-meta-item-text">Disqus：</span><a title="disqus" href="/2018/08/22/JavaScript%E6%9C%89%E7%94%A8%E7%9A%84%E4%BB%A3%E7%A0%81%E7%89%87%E6%AE%B5%E5%92%8Ctrick/#disqus_thread" itemprop="discussionUrl"><span class="post-comments-count disqus-comment-count" data-disqus-identifier="2018/08/22/JavaScript有用的代码片段和trick/" itemprop="commentCount"></span></a></span></div></header><div class="post-body" itemprop="articleBody"><h4 id="浮点数取整"><a href="#浮点数取整" class="headerlink" title="浮点数取整"></a>浮点数取整</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> x = <span class="number">123.4545</span>;</span><br><span class="line">x &gt;&gt; <span class="number">0</span>; <span class="comment">// 123</span></span><br><span class="line">~~x; <span class="comment">// 123</span></span><br><span class="line">x | <span class="number">0</span>; <span class="comment">// 123</span></span><br><span class="line"><span class="built_in">Math</span>.floor(x); <span class="comment">// 123</span></span><br></pre></td></tr></table></figure><blockquote><p>注意：前三种方法只适用于32个位整数，对于负数的处理上和 Math.floor是不同的。</p></blockquote><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.floor(<span class="number">-12.53</span>); <span class="comment">// -13</span></span><br><span class="line"><span class="number">-12.53</span> | <span class="number">0</span>; <span class="comment">// -12</span></span><br></pre></td></tr></table></figure><h4 id="生成6位数字验证码"><a href="#生成6位数字验证码" class="headerlink" title="生成6位数字验证码"></a>生成6位数字验证码</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line">(<span class="string">'000000'</span> + <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() *  <span class="number">999999</span>)).slice(<span class="number">-6</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="built_in">Math</span>.random().toString().slice(<span class="number">-6</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三</span></span><br><span class="line"><span class="built_in">Math</span>.random().toFixed(<span class="number">6</span>).slice(<span class="number">-6</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法四</span></span><br><span class="line"><span class="string">''</span> + <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * <span class="number">999999</span>);</span><br></pre></td></tr></table></figure><h4 id="16进制颜色代码生成"><a href="#16进制颜色代码生成" class="headerlink" title="16进制颜色代码生成"></a>16进制颜色代码生成</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="string">'#'</span>+(<span class="string">'00000'</span>+</span><br><span class="line">    (<span class="built_in">Math</span>.random()*<span class="number">0x1000000</span>&lt;&lt;<span class="number">0</span>).toString(<span class="number">16</span>)).slice(<span class="number">-6</span>);</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure><h4 id="驼峰命名转下划线"><a href="#驼峰命名转下划线" class="headerlink" title="驼峰命名转下划线"></a>驼峰命名转下划线</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'componentMapModelRegistry'</span>.match(<span class="regexp">/^[a-z][a-z0-9]+|[A-Z][a-z0-9]*/g</span>).join(<span class="string">'_'</span>).toLowerCase(); <span class="comment">// component_map_model_registry</span></span><br></pre></td></tr></table></figure><h4 id="url查询参数转json格式"><a href="#url查询参数转json格式" class="headerlink" title="url查询参数转json格式"></a>url查询参数转json格式</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ES6</span></span><br><span class="line"><span class="keyword">const</span> query = <span class="function">(<span class="params">search = <span class="string">''</span></span>) =&gt;</span> <span class="function">(<span class="params">(querystring = <span class="string">''</span></span>) =&gt;</span> (<span class="function"><span class="params">q</span> =&gt;</span> (querystring.split(<span class="string">'&amp;'</span>).forEach(<span class="function"><span class="params">item</span> =&gt;</span> (<span class="function"><span class="params">kv</span> =&gt;</span> kv[<span class="number">0</span>] &amp;&amp; (q[kv[<span class="number">0</span>]] = kv[<span class="number">1</span>]))(item.split(<span class="string">'='</span>))), q))(&#123;&#125;))(search.split(<span class="string">'?'</span>)[<span class="number">1</span>]);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对应ES5实现</span></span><br><span class="line"><span class="keyword">var</span> query = <span class="function"><span class="keyword">function</span>(<span class="params">search</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (search === <span class="keyword">void</span> <span class="number">0</span>) &#123; search = <span class="string">''</span>; &#125;</span><br><span class="line">  <span class="keyword">return</span> (<span class="function"><span class="keyword">function</span>(<span class="params">querystring</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (querystring === <span class="keyword">void</span> <span class="number">0</span>) &#123; querystring = <span class="string">''</span>; &#125;</span><br><span class="line">    <span class="keyword">return</span> (<span class="function"><span class="keyword">function</span>(<span class="params">q</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> (querystring.split(<span class="string">'&amp;'</span>).forEach(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> (<span class="function"><span class="keyword">function</span>(<span class="params">kv</span>) </span>&#123;</span><br><span class="line">          <span class="keyword">return</span> kv[<span class="number">0</span>] &amp;&amp; (q[kv[<span class="number">0</span>]] = kv[<span class="number">1</span>]);</span><br><span class="line">        &#125;)(item.split(<span class="string">'='</span>));</span><br><span class="line">      &#125;), q);</span><br><span class="line">    &#125;)(&#123;&#125;);</span><br><span class="line">  &#125;)(search.split(<span class="string">'?'</span>)[<span class="number">1</span>]);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">query(<span class="string">'?key1=value1&amp;key2=value2'</span>); <span class="comment">// es6.html:14 &#123;key1: "value1", key2: "value2"&#125;</span></span><br></pre></td></tr></table></figure><h4 id="获取URL参数"><a href="#获取URL参数" class="headerlink" title="获取URL参数"></a>获取URL参数</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getQueryString</span>(<span class="params">key</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> reg = <span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">"(^|&amp;)"</span>+ key +<span class="string">"=([^&amp;]*)(&amp;|$)"</span>);</span><br><span class="line">  <span class="keyword">var</span> r = <span class="built_in">window</span>.location.search.substr(<span class="number">1</span>).match(reg);</span><br><span class="line">  <span class="keyword">if</span>(!!r)&#123;</span><br><span class="line">      <span class="keyword">return</span>  <span class="built_in">unescape</span>(r[<span class="number">2</span>]);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="n维数组展开成一维数组"><a href="#n维数组展开成一维数组" class="headerlink" title="n维数组展开成一维数组"></a>n维数组展开成一维数组</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = [<span class="number">1</span>, [<span class="number">2</span>, <span class="number">3</span>], [<span class="string">'4'</span>, <span class="number">5</span>, [<span class="string">'6'</span>,<span class="number">7</span>,[<span class="number">8</span>]]], [<span class="number">9</span>], <span class="number">10</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法一</span></span><br><span class="line"><span class="comment">// 限制：数组项不能出现`,`，同时数组项全部变成了字符数字</span></span><br><span class="line">foo.toString().split(<span class="string">','</span>); <span class="comment">// ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="comment">// 转换后数组项全部变成数字了</span></span><br><span class="line"><span class="built_in">eval</span>(<span class="string">'['</span> + foo + <span class="string">']'</span>); <span class="comment">// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三，使用ES6展开操作符</span></span><br><span class="line"><span class="comment">// 写法太过麻烦，太过死板</span></span><br><span class="line">[<span class="number">1</span>, ...[<span class="number">2</span>, <span class="number">3</span>], ...[<span class="string">'4'</span>, <span class="number">5</span>, ...[<span class="string">'6'</span>,<span class="number">7</span>,...[<span class="number">8</span>]]], ...[<span class="number">9</span>], <span class="number">10</span>]; <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法四</span></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">`[<span class="subst">$&#123;<span class="built_in">JSON</span>.stringify(foo).replace(<span class="regexp">/\[|]/g</span>, <span class="string">''</span>)&#125;</span>]`</span>); <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法五</span></span><br><span class="line"><span class="keyword">const</span> flatten = <span class="function">(<span class="params">ary</span>) =&gt;</span> ary.reduce(<span class="function">(<span class="params">a, b</span>) =&gt;</span> a.concat(<span class="built_in">Array</span>.isArray(b) ? flatten(b) : b), []);</span><br><span class="line">flatten(foo); <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法六</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">flatten</span>(<span class="params">a</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Array</span>.isArray(a) ? [].concat(...a.map(flatten)) : a;</span><br><span class="line">&#125;</span><br><span class="line">flatten(foo); <span class="comment">// [1, 2, 3, "4", 5, "6", 7, 8, 9, 10]</span></span><br></pre></td></tr></table></figure><blockquote><p>注：更多方法请参考《How to flatten nested array in JavaScript?》</p></blockquote><h4 id="日期格式化"><a href="#日期格式化" class="headerlink" title="日期格式化"></a>日期格式化</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">format1</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> z = &#123;</span><br><span class="line">    y: x.getFullYear(),</span><br><span class="line">    M: x.getMonth() + <span class="number">1</span>,</span><br><span class="line">    d: x.getDate(),</span><br><span class="line">    h: x.getHours(),</span><br><span class="line">    m: x.getMinutes(),</span><br><span class="line">    s: x.getSeconds()</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> y.replace(<span class="regexp">/(y+|M+|d+|h+|m+|s+)/g</span>, <span class="function"><span class="keyword">function</span>(<span class="params">v</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> ((v.length &gt; <span class="number">1</span> ? <span class="string">"0"</span> : <span class="string">""</span>) + <span class="built_in">eval</span>(<span class="string">'z.'</span> + v.slice(<span class="number">-1</span>))).slice(-(v.length &gt; <span class="number">2</span> ? v.length : <span class="number">2</span>))</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">format1(<span class="keyword">new</span> <span class="built_in">Date</span>(), <span class="string">'yy-M-d h:m:s'</span>); <span class="comment">// 17-10-14 22:14:41</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="built_in">Date</span>.prototype.format = <span class="function"><span class="keyword">function</span> (<span class="params">fmt</span>) </span>&#123; </span><br><span class="line">  <span class="keyword">var</span> o = &#123;</span><br><span class="line">    <span class="string">"M+"</span>: <span class="keyword">this</span>.getMonth() + <span class="number">1</span>, <span class="comment">//月份 </span></span><br><span class="line">    <span class="string">"d+"</span>: <span class="keyword">this</span>.getDate(), <span class="comment">//日 </span></span><br><span class="line">    <span class="string">"h+"</span>: <span class="keyword">this</span>.getHours(), <span class="comment">//小时 </span></span><br><span class="line">    <span class="string">"m+"</span>: <span class="keyword">this</span>.getMinutes(), <span class="comment">//分 </span></span><br><span class="line">    <span class="string">"s+"</span>: <span class="keyword">this</span>.getSeconds(), <span class="comment">//秒 </span></span><br><span class="line">    <span class="string">"q+"</span>: <span class="built_in">Math</span>.floor((<span class="keyword">this</span>.getMonth() + <span class="number">3</span>) / <span class="number">3</span>), <span class="comment">//季度 </span></span><br><span class="line">    <span class="string">"S"</span>: <span class="keyword">this</span>.getMilliseconds() <span class="comment">//毫秒 </span></span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">if</span> (<span class="regexp">/(y+)/</span>.test(fmt))&#123;</span><br><span class="line">    fmt = fmt.replace(<span class="built_in">RegExp</span>.$<span class="number">1</span>, (<span class="keyword">this</span>.getFullYear() + <span class="string">""</span>).substr(<span class="number">4</span> - <span class="built_in">RegExp</span>.$<span class="number">1.</span>length));</span><br><span class="line">  &#125; </span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> k <span class="keyword">in</span> o)&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">new</span> <span class="built_in">RegExp</span>(<span class="string">"("</span> + k + <span class="string">")"</span>).test(fmt))&#123;</span><br><span class="line">      fmt = fmt.replace(<span class="built_in">RegExp</span>.$<span class="number">1</span>, (<span class="built_in">RegExp</span>.$<span class="number">1.</span>length == <span class="number">1</span>) ? (o[k]) : ((<span class="string">"00"</span> + o[k]).substr((<span class="string">""</span> + o[k]).length)));</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;     </span><br><span class="line">  <span class="keyword">return</span> fmt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>().format(<span class="string">'yy-M-d h:m:s'</span>); <span class="comment">// 17-10-14 22:18:17</span></span><br></pre></td></tr></table></figure><h4 id="统计文字个数"><a href="#统计文字个数" class="headerlink" title="统计文字个数"></a>统计文字个数</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">wordCount</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> pattern = <span class="regexp">/[a-zA-Z0-9_\u0392-\u03c9]+|[\u4E00-\u9FFF\u3400-\u4dbf\uf900-\ufaff\u3040-\u309f\uac00-\ud7af]+/g</span>;</span><br><span class="line">  <span class="keyword">var</span> m = data.match(pattern);</span><br><span class="line">  <span class="keyword">var</span> count = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">if</span>( m === <span class="literal">null</span> ) <span class="keyword">return</span> count;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; m.length; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (m[i].charCodeAt(<span class="number">0</span>) &gt;= <span class="number">0x4E00</span>) &#123;</span><br><span class="line">      count += m[i].length;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      count += <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> count;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> text = <span class="string">'贷款买房，也意味着你能给自己的资产加杠杆，能够撬动更多的钱，来孳生更多的财务性收入。'</span>;</span><br><span class="line">wordCount(text); <span class="comment">// 38</span></span><br></pre></td></tr></table></figure><h4 id="特殊字符转义"><a href="#特殊字符转义" class="headerlink" title="特殊字符转义"></a>特殊字符转义</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">htmlspecialchars</span> (<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> str = str.toString().replace(<span class="regexp">/&amp;/g</span>, <span class="string">"&amp;amp;"</span>).replace(<span class="regexp">/&lt;/g</span>, <span class="string">"&amp;lt;"</span>).replace(<span class="regexp">/&gt;/g</span>, <span class="string">"&amp;gt;"</span>).replace(<span class="regexp">/"/g</span>, <span class="string">'&amp;quot;'</span>);</span><br><span class="line">  <span class="keyword">return</span> str;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">htmlspecialchars(<span class="string">'&amp;jfkds&lt;&gt;'</span>); <span class="comment">// "&amp;amp;jfkds&amp;lt;&amp;gt;"</span></span><br></pre></td></tr></table></figure><h4 id="动态插入js"><a href="#动态插入js" class="headerlink" title="动态插入js"></a>动态插入js</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">injectScript</span>(<span class="params">src</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> s, t;</span><br><span class="line">    s = <span class="built_in">document</span>.createElement(<span class="string">'script'</span>);</span><br><span class="line">    s.type = <span class="string">'text/javascript'</span>;</span><br><span class="line">    s.async = <span class="literal">true</span>;</span><br><span class="line">    s.src = src;</span><br><span class="line">    t = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'script'</span>)[<span class="number">0</span>];</span><br><span class="line">    t.parentNode.insertBefore(s, t);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="格式化数量"><a href="#格式化数量" class="headerlink" title="格式化数量"></a>格式化数量</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatNum</span> (<span class="params">num, n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> num == <span class="string">"number"</span>) &#123;</span><br><span class="line">    num = <span class="built_in">String</span>(num.toFixed(n || <span class="number">0</span>));</span><br><span class="line">    <span class="keyword">var</span> re = <span class="regexp">/(-?\d+)(\d&#123;3&#125;)/</span>;</span><br><span class="line">    <span class="keyword">while</span> (re.test(num)) num = num.replace(re, <span class="string">"$1,$2"</span>);</span><br><span class="line">    <span class="keyword">return</span> num;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> num;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">formatNum(<span class="number">2313123</span>, <span class="number">3</span>); <span class="comment">// "2,313,123.000"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二</span></span><br><span class="line"><span class="string">'2313123'</span>.replace(<span class="regexp">/\B(?=(\d&#123;3&#125;)+(?!\d))/g</span>, <span class="string">','</span>); <span class="comment">// "2,313,123"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatNum</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> str.split(<span class="string">''</span>).reverse().reduce(<span class="function">(<span class="params">prev, next, index</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> ((index % <span class="number">3</span>) ? next : (next + <span class="string">','</span>)) + prev</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">formatNum(<span class="string">'2313323'</span>); <span class="comment">// "2,313,323"</span></span><br></pre></td></tr></table></figure><h4 id="身份证验证"><a href="#身份证验证" class="headerlink" title="身份证验证"></a>身份证验证</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">chechCHNCardId</span>(<span class="params">sNo</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="keyword">this</span>.regExpTest(sNo, /^[<span class="number">0</span><span class="number">-9</span>]&#123;<span class="number">17</span>&#125;[X0<span class="number">-9</span>]$/)) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  sNo = sNo.toString();</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> a, b, c;</span><br><span class="line">  a = <span class="built_in">parseInt</span>(sNo.substr(<span class="number">0</span>, <span class="number">1</span>)) * <span class="number">7</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">1</span>, <span class="number">1</span>)) * <span class="number">9</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">2</span>, <span class="number">1</span>)) * <span class="number">10</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">3</span>, <span class="number">1</span>)) * <span class="number">5</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">4</span>, <span class="number">1</span>)) * <span class="number">8</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">5</span>, <span class="number">1</span>)) * <span class="number">4</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">6</span>, <span class="number">1</span>)) * <span class="number">2</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">7</span>, <span class="number">1</span>)) * <span class="number">1</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">8</span>, <span class="number">1</span>)) * <span class="number">6</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">9</span>, <span class="number">1</span>)) * <span class="number">3</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">10</span>, <span class="number">1</span>)) * <span class="number">7</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">11</span>, <span class="number">1</span>)) * <span class="number">9</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">12</span>, <span class="number">1</span>)) * <span class="number">10</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">13</span>, <span class="number">1</span>)) * <span class="number">5</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">14</span>, <span class="number">1</span>)) * <span class="number">8</span>;</span><br><span class="line">  a = a + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">15</span>, <span class="number">1</span>)) * <span class="number">4</span> + <span class="built_in">parseInt</span>(sNo.substr(<span class="number">16</span>, <span class="number">1</span>)) * <span class="number">2</span>;</span><br><span class="line">  b = a % <span class="number">11</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (b == <span class="number">2</span>) &#123;</span><br><span class="line">    c = sNo.substr(<span class="number">17</span>, <span class="number">1</span>).toUpperCase();</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    c = <span class="built_in">parseInt</span>(sNo.substr(<span class="number">17</span>, <span class="number">1</span>));</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">switch</span> (b) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="string">"X"</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">9</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">8</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">7</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">6</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">7</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">5</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">8</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">4</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">9</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">3</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">10</span>:</span><br><span class="line">      <span class="keyword">if</span> (c != <span class="number">2</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">      &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="测试质数"><a href="#测试质数" class="headerlink" title="测试质数"></a>测试质数</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isPrime</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> !(<span class="regexp">/^.?$|^(..+?)\1+$/</span>).test(<span class="string">'1'</span>.repeat(n))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="统计字符串中相同字符出现的次数"><a href="#统计字符串中相同字符出现的次数" class="headerlink" title="统计字符串中相同字符出现的次数"></a>统计字符串中相同字符出现的次数</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = <span class="string">'abcdaabc'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> info = arr</span><br><span class="line">    .split(<span class="string">''</span>)</span><br><span class="line">    .reduce(<span class="function">(<span class="params">p, k</span>) =&gt;</span> (p[k]++ || (p[k] = <span class="number">1</span>), p), &#123;&#125;);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(info); <span class="comment">//&#123; a: 3, b: 2, c: 2, d: 1 &#125;</span></span><br></pre></td></tr></table></figure><h4 id="使用void-0来解决undefined被污染问题"><a href="#使用void-0来解决undefined被污染问题" class="headerlink" title="使用void 0来解决undefined被污染问题"></a>使用<code>void 0</code>来解决<code>undefined</code>被污染问题</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="literal">undefined</span> = <span class="number">1</span>;</span><br><span class="line">!!<span class="literal">undefined</span>; <span class="comment">// true</span></span><br><span class="line">!!<span class="keyword">void</span>(<span class="number">0</span>); <span class="comment">// false</span></span><br></pre></td></tr></table></figure><h4 id="单行写一个评级组件"><a href="#单行写一个评级组件" class="headerlink" title="单行写一个评级组件"></a>单行写一个评级组件</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"★★★★★☆☆☆☆☆"</span>.slice(<span class="number">5</span> - rate, <span class="number">10</span> - rate);</span><br></pre></td></tr></table></figure><h4 id="JavaScript-错误处理的方式的正确姿势"><a href="#JavaScript-错误处理的方式的正确姿势" class="headerlink" title="JavaScript 错误处理的方式的正确姿势"></a>JavaScript 错误处理的方式的正确姿势</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">    something</span><br><span class="line">&#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">    <span class="built_in">window</span>.location.href =</span><br><span class="line">        <span class="string">"http://stackoverflow.com/search?q=[js]+"</span> +</span><br><span class="line">        e.message;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="匿名函数自执行写法"><a href="#匿名函数自执行写法" class="headerlink" title="匿名函数自执行写法"></a>匿名函数自执行写法</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">( <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;() );</span><br><span class="line">( <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125; )();</span><br><span class="line">[ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;() ];</span><br><span class="line"></span><br><span class="line">~ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line">! <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line">+ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line">- <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"></span><br><span class="line"><span class="keyword">delete</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">typeof</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">void</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">new</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="keyword">new</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> f = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"></span><br><span class="line"><span class="number">1</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="number">1</span> ^ <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br><span class="line"><span class="number">1</span> &gt; <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;();</span><br></pre></td></tr></table></figure><h4 id="两个整数交换数值"><a href="#两个整数交换数值" class="headerlink" title="两个整数交换数值"></a>两个整数交换数值</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">20</span>, b = <span class="number">30</span>;</span><br><span class="line">a ^= b;</span><br><span class="line">b ^= a;</span><br><span class="line">a ^= b;</span><br><span class="line"></span><br><span class="line">a; <span class="comment">// 30</span></span><br><span class="line">b; <span class="comment">// 20</span></span><br></pre></td></tr></table></figure><h4 id="数字字符转数字"><a href="#数字字符转数字" class="headerlink" title="数字字符转数字"></a>数字字符转数字</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">'1'</span>;</span><br><span class="line">+a; <span class="comment">// 1</span></span><br></pre></td></tr></table></figure><h4 id="最短的代码实现数组去重"><a href="#最短的代码实现数组去重" class="headerlink" title="最短的代码实现数组去重"></a>最短的代码实现数组去重</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[...new <span class="built_in">Set</span>([<span class="number">1</span>, <span class="string">"1"</span>, <span class="number">2</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">3</span>])]; <span class="comment">// [1, "1", 2, 3]</span></span><br></pre></td></tr></table></figure><h4 id="用最短的代码实现一个长度为m-6-且值都n-8-的数组"><a href="#用最短的代码实现一个长度为m-6-且值都n-8-的数组" class="headerlink" title="用最短的代码实现一个长度为m(6)且值都n(8)的数组"></a>用最短的代码实现一个长度为m(6)且值都n(8)的数组</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>(<span class="number">6</span>).fill(<span class="number">8</span>); <span class="comment">// [8, 8, 8, 8, 8, 8]</span></span><br></pre></td></tr></table></figure><h4 id="将argruments对象转换成数组"><a href="#将argruments对象转换成数组" class="headerlink" title="将argruments对象转换成数组"></a>将argruments对象转换成数组</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> argArray = <span class="built_in">Array</span>.prototype.slice.call(<span class="built_in">arguments</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// ES6：</span></span><br><span class="line"><span class="keyword">var</span> argArray = <span class="built_in">Array</span>.from(<span class="built_in">arguments</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// or</span></span><br><span class="line"><span class="keyword">var</span> argArray = [...arguments];</span><br></pre></td></tr></table></figure><h4 id="获取日期时间缀"><a href="#获取日期时间缀" class="headerlink" title="获取日期时间缀"></a>获取日期时间缀</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取指定时间的时间缀</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Date</span>().getTime();</span><br><span class="line">(<span class="keyword">new</span> <span class="built_in">Date</span>()).getTime();</span><br><span class="line">(<span class="keyword">new</span> <span class="built_in">Date</span>).getTime();</span><br><span class="line"><span class="comment">// 获取当前的时间缀</span></span><br><span class="line"><span class="built_in">Date</span>.now();</span><br><span class="line"><span class="comment">// 日期显示转换为数字</span></span><br><span class="line">+<span class="keyword">new</span> <span class="built_in">Date</span>();</span><br></pre></td></tr></table></figure><h4 id="使用-x-indexOf-39-y-39-来简化x-indexOf-39-y-39-gt"><a href="#使用-x-indexOf-39-y-39-来简化x-indexOf-39-y-39-gt" class="headerlink" title="使用~x.indexOf(&#39;y&#39;)来简化x.indexOf(&#39;y&#39;) &gt; -"></a>使用<code>~x.indexOf(&#39;y&#39;)</code>来简化<code>x.indexOf(&#39;y&#39;) &gt; -</code></h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">'hello world'</span>;</span><br><span class="line"><span class="keyword">if</span> (str.indexOf(<span class="string">'lo'</span>) &gt; <span class="number">-1</span>) &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (~str.indexOf(<span class="string">'lo'</span>)) &#123;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="parseInt-or-Number"><a href="#parseInt-or-Number" class="headerlink" title="parseInt() or Number()"></a><code>parseInt()</code> or <code>Number()</code></h4><p>两者的差别之处在于<strong>解析</strong>和<strong>转换</strong>两者之间的理解。</p><p>解析<strong>允许</strong>字符串中含有非数字字符，解析按从左到右的顺序，如果遇到非数字字符就停止。而转换<strong>不允许</strong>出现非数字字符，否者会失败并返回NaN。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="string">'520'</span>;</span><br><span class="line"><span class="keyword">var</span> b = <span class="string">'520px'</span>;</span><br><span class="line"></span><br><span class="line"><span class="built_in">Number</span>(a); <span class="comment">// 520</span></span><br><span class="line"><span class="built_in">parseInt</span>(a); <span class="comment">// 520</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">Number</span>(b); <span class="comment">// NaN</span></span><br><span class="line"><span class="built_in">parseInt</span>(b); <span class="comment">// 520</span></span><br></pre></td></tr></table></figure><p><code>parseInt</code>方法第二个参数用于指定转换的基数，ES5默认为10进制。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">2</span>); <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">8</span>); <span class="comment">// 8</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">10</span>); <span class="comment">// 10</span></span><br><span class="line"><span class="built_in">parseInt</span>(<span class="string">'10'</span>, <span class="number">16</span>);  <span class="comment">// 16</span></span><br></pre></td></tr></table></figure><p>对于网上<code>parseInt(0.0000008)</code>的结果为什么为8，原因在于0.0000008转换成字符为”8e-7”，然后根据<code>parseInt</code>的解析规则自然得到”8”这个结果。</p><h4 id="拼接操作，-x-or-String-x-？"><a href="#拼接操作，-x-or-String-x-？" class="headerlink" title="+拼接操作，+x or String(x)？"></a><code>+</code>拼接操作，<code>+x</code> or <code>String(x)</code>？</h4><p>+运算符可用于数字加法，同时也可以用于字符串拼接。如果+的其中一个操作符是字符串(或者通过 隐式强制转换可以得到字符串)，则执行字符串拼接；否者执行数字加法。</p><p>需要注意的时对于数组而言，不能通过<code>valueOf()</code>方法得到简单基本类型值，于是转而调用<code>toString()</code>方法。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>,<span class="number">2</span>] + [<span class="number">3</span>, <span class="number">4</span>]; <span class="comment">// "1,23,4"</span></span><br></pre></td></tr></table></figure><p>对于对象同样会先调用<code>valueOf()</code>方法，然后通过<code>toString()</code>方法返回对象的字符串表示。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = &#123;&#125;;</span><br><span class="line">a + <span class="number">123</span>; <span class="comment">// "[object Object]123"</span></span><br></pre></td></tr></table></figure><p>对于<code>a + &quot;&quot;</code>隐式转换和<code>String(a)</code>显示转换有一个细微的差别：<code>a + &#39;&#39;</code>会对a调用<code>valueOf()</code>方法，而<code>String()</code>直接调用<code>toString()</code>方法。大多数情况下我们不会考虑这个问题，除非真遇到。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a  = &#123;</span><br><span class="line">  valueOf: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="number">42</span>; &#125;,</span><br><span class="line">  toString: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123; <span class="keyword">return</span> <span class="number">4</span>; &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">a + <span class="string">''</span>; <span class="comment">// 42</span></span><br><span class="line"><span class="built_in">String</span>(a); <span class="comment">// 4</span></span><br></pre></td></tr></table></figure><h4 id="判断对象的实例"><a href="#判断对象的实例" class="headerlink" title="判断对象的实例"></a>判断对象的实例</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法一: ES3</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!(<span class="keyword">this</span> <span class="keyword">instanceof</span> Person)) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Person(name, age);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">  <span class="keyword">this</span>.age = age;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法二: ES5</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> self = <span class="keyword">this</span> <span class="keyword">instanceof</span> Person ? <span class="keyword">this</span> : <span class="built_in">Object</span>.create(Person.prototype);</span><br><span class="line">  self.name = name;</span><br><span class="line">  self.age = age;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> self;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法三：ES6</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name, age</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (!<span class="keyword">new</span>.target) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="string">'Peron must called with new'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.name = name;</span><br><span class="line">  <span class="keyword">this</span>.age = age;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="数据安全类型检查"><a href="#数据安全类型检查" class="headerlink" title="数据安全类型检查"></a>数据安全类型检查</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 对象</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isObject</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Object</span>.prototype.toString.call(value).slice(<span class="number">8</span>, <span class="number">-1</span>) === <span class="string">'Object'</span><span class="string">';</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 数组</span></span><br><span class="line"><span class="string">function isArray(value) &#123;</span></span><br><span class="line"><span class="string">  return Object.prototype.toString.call(value).slice(8, -1) === '</span><span class="built_in">Array</span><span class="string">';</span></span><br><span class="line"><span class="string">&#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">// 函数</span></span><br><span class="line"><span class="string">function isFunction(value) &#123;</span></span><br><span class="line"><span class="string">  return Object.prototype.toString.call(value).slice(8, -1) === '</span><span class="built_in">Function</span><span class="string">';</span></span><br><span class="line"><span class="string">&#125;</span></span><br></pre></td></tr></table></figure><h4 id="让数字的字面值看起来像对象"><a href="#让数字的字面值看起来像对象" class="headerlink" title="让数字的字面值看起来像对象"></a>让数字的字面值看起来像对象</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">2.</span>toString(); <span class="comment">// Uncaught SyntaxError: Invalid or unexpected token</span></span><br><span class="line"></span><br><span class="line"><span class="number">2.</span>.toString(); <span class="comment">// 第二个点号可以正常解析</span></span><br><span class="line"><span class="number">2</span> .toString(); <span class="comment">// 注意点号前面的空格</span></span><br><span class="line">(<span class="number">2</span>).toString(); <span class="comment">// 2先被计算</span></span><br></pre></td></tr></table></figure><h4 id="对象可计算属性名-仅在ES6中"><a href="#对象可计算属性名-仅在ES6中" class="headerlink" title="对象可计算属性名(仅在ES6中)"></a>对象可计算属性名(仅在ES6中)</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> suffix = <span class="string">' name'</span>;</span><br><span class="line"><span class="keyword">var</span> person = &#123;</span><br><span class="line">  [<span class="string">'first'</span> + suffix]: <span class="string">'Nicholas'</span>,</span><br><span class="line">  [<span class="string">'last'</span> + suffix]: <span class="string">'Zakas'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">person[<span class="string">'first name'</span>]; <span class="comment">// "Nicholas"</span></span><br><span class="line">person[<span class="string">'last name'</span>]; <span class="comment">// "Zakas"</span></span><br></pre></td></tr></table></figure><h4 id="数字四舍五入"><a href="#数字四舍五入" class="headerlink" title="数字四舍五入"></a>数字四舍五入</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// v: 值，p: 精度</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> (<span class="params">v, p</span>) </span>&#123;</span><br><span class="line">  p = <span class="built_in">Math</span>.pow(<span class="number">10</span>, p &gt;&gt;&gt; <span class="number">31</span> ? <span class="number">0</span> : p | <span class="number">0</span>)</span><br><span class="line">  v *= p;</span><br><span class="line">  <span class="keyword">return</span> (v + <span class="number">0.5</span> + (v &gt;&gt; <span class="number">31</span>) | <span class="number">0</span>) / p</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">round(<span class="number">123.45353</span>, <span class="number">2</span>); <span class="comment">// 123.45</span></span><br></pre></td></tr></table></figure><h4 id="在浏览器中根据url下载文件"><a href="#在浏览器中根据url下载文件" class="headerlink" title="在浏览器中根据url下载文件"></a>在浏览器中根据url下载文件</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">download</span>(<span class="params">url</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> isChrome = navigator.userAgent.toLowerCase().indexOf(<span class="string">'chrome'</span>) &gt; <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">var</span> isSafari = navigator.userAgent.toLowerCase().indexOf(<span class="string">'safari'</span>) &gt; <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (isChrome || isSafari) &#123;</span><br><span class="line">    <span class="keyword">var</span> link = <span class="built_in">document</span>.createElement(<span class="string">'a'</span>);</span><br><span class="line">    link.href = url;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (link.download !== <span class="literal">undefined</span>) &#123;</span><br><span class="line">      <span class="keyword">var</span> fileName = url.substring(url.lastIndexOf(<span class="string">'/'</span>) + <span class="number">1</span>, url.length);</span><br><span class="line">      link.download = fileName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">document</span>.createEvent) &#123;</span><br><span class="line">      <span class="keyword">var</span> e = <span class="built_in">document</span>.createEvent(<span class="string">'MouseEvents'</span>);</span><br><span class="line">      e.initEvent(<span class="string">'click'</span>, <span class="literal">true</span>, <span class="literal">true</span>);</span><br><span class="line">      link.dispatchEvent(e);</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (url.indexOf(<span class="string">'?'</span>) === <span class="number">-1</span>) &#123;</span><br><span class="line">    url += <span class="string">'?download'</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">window</span>.open(url, <span class="string">'_self'</span>);</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="快速生成UUID"><a href="#快速生成UUID" class="headerlink" title="快速生成UUID"></a>快速生成UUID</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">uuid</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> d = <span class="keyword">new</span> <span class="built_in">Date</span>().getTime();</span><br><span class="line">  <span class="keyword">var</span> uuid = <span class="string">'xxxxxxxxxxxx-4xxx-yxxx-xxxxxxxxxxxx'</span>.replace(<span class="regexp">/[xy]/g</span>, <span class="function"><span class="keyword">function</span>(<span class="params">c</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> r = (d + <span class="built_in">Math</span>.random() * <span class="number">16</span>) % <span class="number">16</span> | <span class="number">0</span>;</span><br><span class="line">    d = <span class="built_in">Math</span>.floor(d / <span class="number">16</span>);</span><br><span class="line">    <span class="keyword">return</span> (c == <span class="string">'x'</span> ? r : (r &amp; <span class="number">0x3</span> | <span class="number">0x8</span>)).toString(<span class="number">16</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> uuid;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">uuid(); <span class="comment">// "33f7f26656cb-499b-b73e-89a921a59ba6"</span></span><br></pre></td></tr></table></figure><h4 id="JavaScript浮点数精度问题"><a href="#JavaScript浮点数精度问题" class="headerlink" title="JavaScript浮点数精度问题"></a>JavaScript浮点数精度问题</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isEqual</span>(<span class="params">n1, n2, epsilon</span>) </span>&#123;</span><br><span class="line">  epsilon = epsilon == <span class="literal">undefined</span> ? <span class="number">10</span> : epsilon; <span class="comment">// 默认精度为10</span></span><br><span class="line">  <span class="keyword">return</span> n1.toFixed(epsilon) === n2.toFixed(epsilon);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="number">0.1</span> + <span class="number">0.2</span>; <span class="comment">// 0.30000000000000004</span></span><br><span class="line">isEqual(<span class="number">0.1</span> + <span class="number">0.2</span>, <span class="number">0.3</span>); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="number">0.7</span> + <span class="number">0.1</span> + <span class="number">99.1</span> + <span class="number">0.1</span>; <span class="comment">// 99.99999999999999</span></span><br><span class="line">isEqual(<span class="number">0.7</span> + <span class="number">0.1</span> + <span class="number">99.1</span> + <span class="number">0.1</span>, <span class="number">100</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure><h4 id="格式化表单数据"><a href="#格式化表单数据" class="headerlink" title="格式化表单数据"></a>格式化表单数据</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">formatParam</span>(<span class="params">obj</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> query = <span class="string">''</span>, name, value, fullSubName, subName, subValue, innerObj, i;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span>(name <span class="keyword">in</span> obj) &#123;</span><br><span class="line">    value = obj[name];</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(value <span class="keyword">instanceof</span> <span class="built_in">Array</span>) &#123;</span><br><span class="line">      <span class="keyword">for</span>(i=<span class="number">0</span>; i&lt;value.length; ++i) &#123;</span><br><span class="line">        subValue = value[i];</span><br><span class="line">        fullSubName = name + <span class="string">'['</span> + i + <span class="string">']'</span>;</span><br><span class="line">        innerObj = &#123;&#125;;</span><br><span class="line">        innerObj[fullSubName] = subValue;</span><br><span class="line">        query += formatParam(innerObj) + <span class="string">'&amp;'</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span>(value <span class="keyword">instanceof</span> <span class="built_in">Object</span>) &#123;</span><br><span class="line">      <span class="keyword">for</span>(subName <span class="keyword">in</span> value) &#123;</span><br><span class="line">        subValue = value[subName];</span><br><span class="line">        fullSubName = name + <span class="string">'['</span> + subName + <span class="string">']'</span>;</span><br><span class="line">        innerObj = &#123;&#125;;</span><br><span class="line">        innerObj[fullSubName] = subValue;</span><br><span class="line">        query += formatParam(innerObj) + <span class="string">'&amp;'</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span>(value !== <span class="literal">undefined</span> &amp;&amp; value !== <span class="literal">null</span>)</span><br><span class="line">      query += <span class="built_in">encodeURIComponent</span>(name) + <span class="string">'='</span> + <span class="built_in">encodeURIComponent</span>(value) + <span class="string">'&amp;'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> query.length ? query.substr(<span class="number">0</span>, query.length - <span class="number">1</span>) : query;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> param = &#123;</span><br><span class="line">  name: <span class="string">'jenemy'</span>,</span><br><span class="line">  likes: [<span class="number">0</span>, <span class="number">1</span>, <span class="number">3</span>],</span><br><span class="line">  memberCard: [</span><br><span class="line">    &#123; <span class="attr">title</span>: <span class="string">'1'</span>, <span class="attr">id</span>: <span class="number">1</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">title</span>: <span class="string">'2'</span>, <span class="attr">id</span>: <span class="number">2</span> &#125;</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">formatParam(param); <span class="comment">// "name=12&amp;likes%5B0%5D=0&amp;likes%5B1%5D=1&amp;likes%5B2%5D=3&amp;memberCard%5B0%5D%5Btitle%5D=1&amp;memberCard%5B0%5D%5Bid%5D=1&amp;memberCard%5B1%5D%5Btitle%5D=2&amp;memberCard%5B1%5D%5Bid%5D=2"</span></span><br></pre></td></tr></table></figure><h4 id="创建指定长度非空数组"><a href="#创建指定长度非空数组" class="headerlink" title="创建指定长度非空数组"></a>创建指定长度非空数组</h4><p>在JavaScript中可以通过<code>new Array(3)</code>的形式创建一个长度为3的空数组。在老的Chrome中其值为[undefined x 3]，在最新的Chrome中为[empty x 3]，即空单元数组。在老Chrome中，相当于显示使用<code>[undefined, undefined, undefined]</code>的方式创建长度为3的数组。</p><p>但是，两者在调用<code>map()</code>方法的结果是明显不同的</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">3</span>);</span><br><span class="line"><span class="keyword">var</span> b = [<span class="literal">undefined</span>, <span class="literal">undefined</span>, <span class="literal">undefined</span>];</span><br><span class="line"></span><br><span class="line">a.map(<span class="function">(<span class="params">v, i</span>) =&gt;</span> i); <span class="comment">// [empty × 3]</span></span><br><span class="line">b.map(<span class="function">(<span class="params">v, i</span>) =&gt;</span> i); <span class="comment">// [0, 1, 2]</span></span><br></pre></td></tr></table></figure><p>多数情况我们期望创建的是包含<code>undefined</code>值的指定长度的空数组，可以通过下面这种方法来达到目的：</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="built_in">Array</span>.apply(<span class="literal">null</span>, &#123; <span class="attr">length</span>: <span class="number">3</span> &#125;);</span><br><span class="line"></span><br><span class="line">a; <span class="comment">// [undefined, undefined, undefined]</span></span><br><span class="line">a.map(<span class="function">(<span class="params">v, i</span>) =&gt;</span> i); <span class="comment">// [0, 1, 2]</span></span><br></pre></td></tr></table></figure><p>总之，尽量不要创建和使用空单元数组。</p><h4 id="debounce方法"><a href="#debounce方法" class="headerlink" title="debounce方法"></a>debounce方法</h4><p><code>debounce()</code>方法用来延迟执行函数。</p><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> debounce = <span class="function"><span class="keyword">function</span> (<span class="params">func, threshold, execAsap</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> timeout;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">debounced</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> obj = <span class="keyword">this</span>, args = <span class="built_in">arguments</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">delayed</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (!execAsap)</span><br><span class="line">        func.apply(obj, args);</span><br><span class="line">      timeout = <span class="literal">null</span>;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (timeout)</span><br><span class="line">      clearTimeout(timeout);</span><br><span class="line">    <span class="keyword">else</span> <span class="keyword">if</span> (execAsap)</span><br><span class="line">      func.apply(obj, args);</span><br><span class="line"></span><br><span class="line">    timeout = setTimeout(delayed, threshold || <span class="number">100</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><h4 id="判断客户端"><a href="#判断客户端" class="headerlink" title="判断客户端"></a>判断客户端</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> browser = &#123;</span><br><span class="line">    v: (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">var</span> u = navigator.userAgent,</span><br><span class="line">            app = navigator.appVersion,</span><br><span class="line">            p = navigator.platform;</span><br><span class="line">        <span class="keyword">return</span> &#123;</span><br><span class="line">            trident: u.indexOf(<span class="string">'Trident'</span>) &gt; <span class="number">-1</span>, <span class="comment">//IE内核</span></span><br><span class="line">            presto: u.indexOf(<span class="string">'Presto'</span>) &gt; <span class="number">-1</span>, <span class="comment">//opera内核</span></span><br><span class="line">            webKit: u.indexOf(<span class="string">'AppleWebKit'</span>) &gt; <span class="number">-1</span>, <span class="comment">//苹果、谷歌内核</span></span><br><span class="line">            gecko: u.indexOf(<span class="string">'Gecko'</span>) &gt; <span class="number">-1</span> &amp;&amp; u.indexOf(<span class="string">'KHTML'</span>) == <span class="number">-1</span>, <span class="comment">//火狐内核</span></span><br><span class="line">            mobile: !!u.match(<span class="regexp">/AppleWebKit.*Mobile.*/</span>), <span class="comment">//是否为移动终端</span></span><br><span class="line">            ios: !!u.match(<span class="regexp">/i[^;]+;( U;)? CPU.+Mac OS X/</span>), <span class="comment">//ios终端</span></span><br><span class="line">            android: u.indexOf(<span class="string">'Android'</span>) &gt; <span class="number">-1</span> || u.indexOf(<span class="string">'Linux'</span>) &gt; <span class="number">-1</span>, <span class="comment">//android终端或uc浏览器</span></span><br><span class="line">            iPhone: u.indexOf(<span class="string">'iPhone'</span>) &gt; <span class="number">-1</span>, <span class="comment">//是否为iPhone或者QQHD浏览器</span></span><br><span class="line">            iPad: u.indexOf(<span class="string">'iPad'</span>) &gt; <span class="number">-1</span>, <span class="comment">//是否iPad</span></span><br><span class="line">            weixin: u.indexOf(<span class="string">'MicroMessenger'</span>) &gt; <span class="number">-1</span>, <span class="comment">//是否微信</span></span><br><span class="line">            webApp: u.indexOf(<span class="string">'Safari'</span>) == <span class="number">-1</span>, <span class="comment">//是否web应该程序，没有头部与底部</span></span><br><span class="line">            UCB: u.match(<span class="regexp">/UCBrowser/i</span>) == <span class="string">"UCBrowser"</span>,</span><br><span class="line">            QQB: u.match(<span class="regexp">/MQQBrowser/i</span>) == <span class="string">"MQQBrowser"</span>,</span><br><span class="line">            win: p.indexOf(<span class="string">'Win'</span>) &gt; <span class="number">-1</span>, <span class="comment">//判断是否是WIN操作系统</span></span><br><span class="line">            mac: p.indexOf(<span class="string">'Mac'</span>) &gt; <span class="number">-1</span> <span class="comment">//判断是否是Mac操作系统</span></span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;)()</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div><div class="reward-container"><div></div> <button onclick='var qr=document.getElementById("qr");qr.style.display="none"===qr.style.display?"block":"none"'> 打赏</button><div id="qr" style="display:none"><div style="display:inline-block"> <img src="/uploads/wechatpay.jpeg" alt="csjiabin 微信支付"><p>微信支付</p></div></div></div><footer class="post-footer"><div class="post-tags"><a href="/tags/js/" rel="tag"><i class="fa fa-tag"></i> js</a></div><div class="post-widgets"><div class="wp_rating"><div id="wpac-rating"></div></div></div><div class="post-nav"><div class="post-nav-item"><a href="/2018/08/18/%E7%94%A8%E5%9B%BE%E6%A0%87%E5%92%8C%E7%A4%BA%E4%BE%8B%E8%A7%A3%E9%87%8AAwait%E5%92%8CAsync/" rel="prev" title="用图标和示例解释Await和Async"><i class="fa fa-chevron-left"></i> 用图标和示例解释Await和Async</a></div><div class="post-nav-item"> <a href="/2018/08/26/Markdown%E4%BD%BF%E7%94%A8%E6%8C%87%E5%8D%97/" rel="next" title="Markdown使用指南">Markdown使用指南<i class="fa fa-chevron-right"></i></a></div></div></footer></article></div><div class="comments"><div id="disqus_thread"><noscript>Please enable JavaScript to view the comments powered by Disqus.</noscript></div></div><script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script></div><div class="toggle sidebar-toggle"><span class="toggle-line toggle-line-first"></span><span class="toggle-line toggle-line-middle"></span><span class="toggle-line toggle-line-last"></span></div><aside class="sidebar"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc"> 文章目录</li><li class="sidebar-nav-overview"> 站点概览</li></ul><div class="post-toc-wrap sidebar-panel"><div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#浮点数取整"><span class="nav-number">1.</span> <span class="nav-text">浮点数取整</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#生成6位数字验证码"><span class="nav-number">2.</span> <span class="nav-text">生成6位数字验证码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#16进制颜色代码生成"><span class="nav-number">3.</span> <span class="nav-text">16进制颜色代码生成</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#驼峰命名转下划线"><span class="nav-number">4.</span> <span class="nav-text">驼峰命名转下划线</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#url查询参数转json格式"><span class="nav-number">5.</span> <span class="nav-text">url查询参数转json格式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取URL参数"><span class="nav-number">6.</span> <span class="nav-text">获取URL参数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#n维数组展开成一维数组"><span class="nav-number">7.</span> <span class="nav-text">n维数组展开成一维数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#日期格式化"><span class="nav-number">8.</span> <span class="nav-text">日期格式化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#统计文字个数"><span class="nav-number">9.</span> <span class="nav-text">统计文字个数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#特殊字符转义"><span class="nav-number">10.</span> <span class="nav-text">特殊字符转义</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#动态插入js"><span class="nav-number">11.</span> <span class="nav-text">动态插入js</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#格式化数量"><span class="nav-number">12.</span> <span class="nav-text">格式化数量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#身份证验证"><span class="nav-number">13.</span> <span class="nav-text">身份证验证</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#测试质数"><span class="nav-number">14.</span> <span class="nav-text">测试质数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#统计字符串中相同字符出现的次数"><span class="nav-number">15.</span> <span class="nav-text">统计字符串中相同字符出现的次数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用void-0来解决undefined被污染问题"><span class="nav-number">16.</span> <span class="nav-text">使用void 0来解决undefined被污染问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#单行写一个评级组件"><span class="nav-number">17.</span> <span class="nav-text">单行写一个评级组件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JavaScript-错误处理的方式的正确姿势"><span class="nav-number">18.</span> <span class="nav-text">JavaScript 错误处理的方式的正确姿势</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#匿名函数自执行写法"><span class="nav-number">19.</span> <span class="nav-text">匿名函数自执行写法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#两个整数交换数值"><span class="nav-number">20.</span> <span class="nav-text">两个整数交换数值</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数字字符转数字"><span class="nav-number">21.</span> <span class="nav-text">数字字符转数字</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#最短的代码实现数组去重"><span class="nav-number">22.</span> <span class="nav-text">最短的代码实现数组去重</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#用最短的代码实现一个长度为m-6-且值都n-8-的数组"><span class="nav-number">23.</span> <span class="nav-text">用最短的代码实现一个长度为m(6)且值都n(8)的数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#将argruments对象转换成数组"><span class="nav-number">24.</span> <span class="nav-text">将argruments对象转换成数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#获取日期时间缀"><span class="nav-number">25.</span> <span class="nav-text">获取日期时间缀</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用-x-indexOf-39-y-39-来简化x-indexOf-39-y-39-gt"><span class="nav-number">26.</span> <span class="nav-text">使用~x.indexOf(&#39;y&#39;)来简化x.indexOf(&#39;y&#39;) &gt; -</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#parseInt-or-Number"><span class="nav-number">27.</span> <span class="nav-text">parseInt() or Number()</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#拼接操作，-x-or-String-x-？"><span class="nav-number">28.</span> <span class="nav-text">+拼接操作，+x or String(x)？</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断对象的实例"><span class="nav-number">29.</span> <span class="nav-text">判断对象的实例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数据安全类型检查"><span class="nav-number">30.</span> <span class="nav-text">数据安全类型检查</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#让数字的字面值看起来像对象"><span class="nav-number">31.</span> <span class="nav-text">让数字的字面值看起来像对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#对象可计算属性名-仅在ES6中"><span class="nav-number">32.</span> <span class="nav-text">对象可计算属性名(仅在ES6中)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数字四舍五入"><span class="nav-number">33.</span> <span class="nav-text">数字四舍五入</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#在浏览器中根据url下载文件"><span class="nav-number">34.</span> <span class="nav-text">在浏览器中根据url下载文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#快速生成UUID"><span class="nav-number">35.</span> <span class="nav-text">快速生成UUID</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JavaScript浮点数精度问题"><span class="nav-number">36.</span> <span class="nav-text">JavaScript浮点数精度问题</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#格式化表单数据"><span class="nav-number">37.</span> <span class="nav-text">格式化表单数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#创建指定长度非空数组"><span class="nav-number">38.</span> <span class="nav-text">创建指定长度非空数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#debounce方法"><span class="nav-number">39.</span> <span class="nav-text">debounce方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#判断客户端"><span class="nav-number">40.</span> <span class="nav-text">判断客户端</span></a></li></ol></div></div><div class="site-overview-wrap sidebar-panel"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"> <img class="site-author-image" itemprop="image" alt="csjiabin" src="https://avatars0.githubusercontent.com/u/20592953"><p class="site-author-name" itemprop="name">csjiabin</p><div class="site-description" itemprop="description">I never consider ease and joyfulness as the purpose of life itself.</div></div><div class="site-state-wrap motion-element"><nav class="site-state"><div class="site-state-item site-state-posts"> <a href="/archives/"><span class="site-state-item-count">17</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"> <a href="/categories/"><span class="site-state-item-count">7</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"> <a href="/tags/"><span class="site-state-item-count">31</span> <span class="site-state-item-name">标签</span></a></div></nav></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/csjiabin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;csjiabin" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i> GitHub</a></span><span class="links-of-author-item"><a href="mailto:qq1187712426@gmail.com" title="E-Mail → mailto:qq1187712426@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i> E-Mail</a></span></div></div></div></aside><div id="sidebar-dimmer"></div></div></main><footer class="footer"><div class="footer-inner"><div class="copyright"> &copy; 2018 – <span itemprop="copyrightYear">2020</span><span class="with-love"><i class="fa fa-heart"></i></span> <span class="author" itemprop="copyrightHolder">csjiabin</span></div><div class="busuanzi-count"><script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="post-meta-item" id="busuanzi_container_site_uv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-user"></i></span><span class="site-uv" title="总访客量"><span id="busuanzi_value_site_uv"></span></span></span> <span class="post-meta-divider">|</span><span class="post-meta-item" id="busuanzi_container_site_pv" style="display:none"><span class="post-meta-item-icon"><i class="fa fa-eye"></i></span><span class="site-pv" title="总访问量"><span id="busuanzi_value_site_pv"></span></span></span></div><div style="display:none"><script src="//s95.cnzz.com/z_stat.php?id=1187712426&web_id=1187712426"></script></div></div></footer></div><script src="/lib/anime.min.js"></script><script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script><script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script><script src="//cdn.jsdelivr.net/npm/lozad/dist/lozad.min.js"></script><script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script><script src="/lib/velocity/velocity.min.js"></script><script src="/lib/velocity/velocity.ui.min.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/pisces.js"></script><script src="/js/next-boot.js"></script><script>CONFIG.page.isPost&&(wpac_init=window.wpac_init||[],wpac_init.push({widget:"Rating",id:13858,el:"wpac-rating",color:"fc6423"}),function(){if(!("WIDGETPACK_LOADED"in window)){WIDGETPACK_LOADED=!0;var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src="//embed.widgetpack.com/widget.js";var t=document.getElementsByTagName("script")[0];t.parentNode.insertBefore(e,t.nextSibling)}}())</script><script src="//cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script><script src="//cdn.jsdelivr.net/npm/instantsearch.js@4/dist/instantsearch.production.min.js"></script><script src="/js/algolia-search.js"></script><script>
document.querySelectorAll('.pdfobject-container').forEach(element => {
  let url = element.dataset.target;
  let pdfOpenParams = {
    navpanes : 0,
    toolbar  : 0,
    statusbar: 0,
    pagemode : 'thumbs',
    view     : 'FitH'
  };
  let pdfOpenFragment = '#' + Object.entries(pdfOpenParams).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&');
  let fullURL = `/lib/pdf/web/viewer.html?file=${encodeURIComponent(url)}${pdfOpenFragment}`;

  if (NexT.utils.supportsPDFs()) {
    element.innerHTML = `<embed class="pdfobject" src="${url + pdfOpenFragment}" type="application/pdf" style="height: ${element.dataset.height};">`;
  } else {
    element.innerHTML = `<iframe src="${fullURL}" style="height: ${element.dataset.height};" frameborder="0"></iframe>`;
  }
});
</script><script>function loadCount(){var d=document,n=d.createElement("script");n.src="https://csjiabin.disqus.com/count.js",n.id="dsq-count-scr",(d.head||d.body).appendChild(n)}window.addEventListener("load",loadCount,!1)</script><script>
  var disqus_config = function() {
    this.page.url = "https://csjiabin.github.io/2018/08/22/JavaScript%E6%9C%89%E7%94%A8%E7%9A%84%E4%BB%A3%E7%A0%81%E7%89%87%E6%AE%B5%E5%92%8Ctrick/";
    this.page.identifier = "2018/08/22/JavaScript有用的代码片段和trick/";
    this.page.title = "JavaScript有用的代码片段和trick";
    };
  NexT.utils.loadComments(document.querySelector('#disqus_thread'), () => {
    if (window.DISQUS) {
      DISQUS.reset({
        reload: true,
        config: disqus_config
      });
    } else {
      var d = document, s = d.createElement('script');
      s.src = 'https://csjiabin.disqus.com/embed.js';
      s.setAttribute('data-timestamp', '' + +new Date());
      (d.head || d.body).appendChild(s);
    }
  });
</script><script type="text/javascript" src="/js/love.js"></script></body></html>